import os
import re
import datetime


def read_section_from_md(file_path, section_name):
    """从指定的markdown文件中读取某个模块的内容。"""
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    pattern = rf"\n# {section_name}\n(.*?)\n# "  # 匹配该模块直到下一个标题
    match = re.search(pattern, content, re.DOTALL)
    if match:
        # 将模块内容按行分割，并忽略表头行
        return set(line.strip() for line in match.group(1).strip().splitlines()[2:])
    return set()


def compare_sections(section_name, previous_set, current_set):
    """比较两个集合，找出新增和减少的条目。"""
    added = current_set - previous_set
    removed = previous_set - current_set

    lines = [f"## {section_name} Changes\n"]
    if added:
        lines.append("### Added Entries")
        for entry in added:
            lines.append(f"- {entry}")
    if removed:
        lines.append("### Removed Entries")
        for entry in removed:
            lines.append(f"- {entry}")
    if not added and not removed:
        lines.append("No changes detected.")
    lines.append("")  # 添加空行分隔不同的模块
    return lines


def analyze_user_data_changes(file_names):
    """分析一系列文件中的用户数据变化情况，生成变化描述的 markdown 文件。"""
    base_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "logs")  # logs目录路径
    user_name = os.path.basename(file_names[0]).split('_')[0]   # 提取用户名
    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H-%M-%S')
    output_file = os.path.join(base_dir, f"{user_name}_data_analysis_{timestamp}.md")

    with open(output_file, 'w', encoding='utf-8') as output_md:
        for i in range(len(file_names) - 1):
            prev_file = os.path.join(base_dir, file_names[i])
            curr_file = os.path.join(base_dir, file_names[i + 1])
            output_md.write(f"# Changes from {file_names[i]} to {file_names[i + 1]}\n\n")

            # 对比每个模块
            for section in ["Solved Problems", "User Recommendation Pool", "User Undo Pool"]:
                prev_section = read_section_from_md(prev_file, section)
                curr_section = read_section_from_md(curr_file, section)
                changes = compare_sections(section, prev_section, curr_section)
                output_md.writelines(f"{line}\n" for line in changes)

            output_md.write("\n")  # 每组文件比较结果后增加一个空行分隔

    print(f"Analysis report generated at {output_file}")



